﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
using System.Net.Http.Headers;

namespace SmartAgricultureService.Core
{
    public static class Utils
    {
        public static IServiceCollection Services { get; internal set; }
        private static readonly HttpClient HttpClient = new();
        public static async Task<bool> IsMatchArea(this DatabaseContext database, string areaCode)
        {
            try
            {
                var httpContextAccessor = Services.BuildServiceProvider().GetService<IHttpContextAccessor>();
                httpContextAccessor.HttpContext.Request.Headers.TryGetValue("Authorization", out StringValues sv);
                var key = sv.ToString().Trim();
                var deviceEntry = await database.Devices.Include(o => o.Area).AsNoTracking().FirstOrDefaultAsync(x => key.EndsWith(x.Token));
                if (deviceEntry != null)
                {
                    if (deviceEntry.Area.Code.Equals("all", StringComparison.CurrentCultureIgnoreCase))
                        return true;
                    else if (deviceEntry.Area.Code == areaCode)
                        return true;
                }
            }
            catch (Exception ex)
            {
                Logger.Instance.LogError("IsDeviceMatchArea", ex);
            }
            return false;
        }
        public static IQueryable<T> Paging<T>(this IQueryable<T> source, int pageIndex, int pageSize, out int total)
        {
            total = source.Count();
            return source.Skip((pageIndex - 1) * pageSize).Take(pageSize);
        }
        public static async Task<string> GetAnswer(string content)
        {
            var result = string.Empty;
            try
            {
                var stringContent = new StringContent(JsonConvert.SerializeObject(new { content }));
                stringContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                var response = await HttpClient.PostAsync("https://dovetm.top/common/api/v1/spark/translateVoiceContent", stringContent);
                if (response.IsSuccessStatusCode)
                    result = await response.Content.ReadAsStringAsync();
            }
            catch (Exception ex)
            {
                Logger.Instance.LogError("GetAnswer", ex);
            }
            return result;
        }
    }
}